//author:kakake
//1.预约挂号支付，调起收银台支付，支付成功后会回调通知tspaynotifyController
//2.预约挂号退费，调起退费接口，退款成功后会回调通知tspaynotifyController
//3.自助缴费支付，调起收银台支付，支付成功后会回调通知tspaynotifyController

//author:kakake
var Common = /** @class */ (function () {
    function Common() {
    }
    return Common;
}());

//author:kakake
var tsregisterController = /** @class */ (function () {
    function tsregisterController() {
        this.data = {
            dbConn: TSLobsterAPI.Program.GetDbConn(),
            WorkId: 1,
            AppId: 1
        };
        //界面医生列表模型
        this.vo_doctorlist = {
            DoctId: 0,
            DeptId: 0,
            RegDate: '',
            HeadImg: '',
            RankName: '',
            DeptName: '',
            DocName: '',
            Describe: '',
            IsHave: 0,
            IsFull: 0,
            AllCount: 0,
            HaveCount: 0 //剩余号源数
        };
        //界面医生页面排班模型
        this.vo_doctorschedule = {
            DoctId: 0,
            DeptId: 0,
            DeptName: '',
            DocName: '',
            RegId: 0,
            Week: '',
            RegFee: 0,
            TimeType: 1,
            RegDate: '',
            IsHave: 0,
            IsFull: 0,
            AllCount: 0,
            HaveCount: 0 //剩余号源数
        };
        //界面显示号源时段，可以配置成精确到每小时
        this.vo_doctorrange = {
            Timeid: 0,
            RegId: 0,
            DoctId: 0,
            DeptId: 0,
            DeptName: '',
            DocName: '',
            RegDate: '',
            IsHave: 0,
            HaveCount: 0,
            AllCount: 0,
            IsAll: 0,
            Status: 0,
            IsExpire: 0,
            Week: '',
            RegFee: 0,
            TimeType: 1,
            StartTime: '',
            EndTime: ''
        };
        this.data.WorkId = TSLobsterAPI.Program.GetWorkId();
        this.hisinterface = new tshisinterfaceController(1);
        this.service = new tsregisterService(this.data.WorkId);
        this.dao = new tsregisterDao(this.data.WorkId);
    }
    //获取科室
    tsregisterController.prototype.depttree = function () {
        //return this.hisinterface.getdept();
        return this.dao.getdept();
    };
    //获取医生列表
    tsregisterController.prototype.getDoctorList = function () {
        var pageInfo = {
            key: "Id desc",
            page: TSLobsterAPI.Program.RequestQuery("page", "1"),
            perPage: TSLobsterAPI.Program.RequestQuery("limit", "10"),
            totalRecord: 100
        };
        var search = TSLobsterAPI.Program.RequestQuery("search", "");
        return this.dao.getDoctorPageList(pageInfo, search);
    };
    //医生信息
    tsregisterController.prototype.doctorInfo = function () {
        var deptId = TSLobsterAPI.Program.RequestQuery("deptId");
        var doctId = TSLobsterAPI.Program.RequestQuery("doctId");
        var data = this.dao.getDoctorInfo(parseInt(doctId));
        return { info: data };
    };
    //从his接口获取科室排班数据
    tsregisterController.prototype.getAllSchedule = function () {
        var deptId = TSLobsterAPI.Program.RequestQuery("deptId");
        // let allschedulelist = this.hisinterface.getdocOrderSched(deptId);
        var allschedulelist = this.dao.getdocOrderSched(0, deptId);
        //存入缓存
        TSLobsterAPI.Utils.setsessioncache('allschedulelist_' + deptId, JSON.stringify(allschedulelist));
        return { list: allschedulelist };
    };
    //获取单日医生排班数据
    tsregisterController.prototype.daySchedule = function () {
        var _this = this;
        var daytime = TSLobsterAPI.Program.RequestQuery("date", "");
        var deptId = TSLobsterAPI.Program.RequestQuery("deptId");
        var alldoctorlist = this.dao.getDoctorList(parseInt(deptId)) || [];
        var allschedulelist = JSON.parse(TSLobsterAPI.Utils.getsessioncache('allschedulelist_' + deptId));
        var scheduledata = [];
        if (daytime == "") { //全部
            alldoctorlist.forEach(function (item) {
                _this.vo_doctorlist.DeptId = item.DeptId;
                _this.vo_doctorlist.DoctId = item.EmpId;
                _this.vo_doctorlist.RegDate = '';
                _this.vo_doctorlist.DeptName = item.DeptName;
                _this.vo_doctorlist.DocName = item.EmpName;
                _this.vo_doctorlist.Describe = item.Describe;
                _this.vo_doctorlist.RankName = item.DoctorPost;
                _this.vo_doctorlist.HeadImg = item.HeadImg;
                var result = _this.service.countSchedule(allschedulelist, item.EmpId); //计算
                _this.vo_doctorlist.IsHave = result.IsHave;
                _this.vo_doctorlist.IsFull = result.IsFull; //计算
                _this.vo_doctorlist.HaveCount = result.HaveCount; //计算
                _this.vo_doctorlist.AllCount = result.AllCount;
                scheduledata.push(JSON.parse(JSON.stringify(_this.vo_doctorlist)));
            });
        }
        else {
            alldoctorlist.forEach(function (item) {
                _this.vo_doctorlist.DeptId = item.DeptId;
                _this.vo_doctorlist.DoctId = item.EmpId;
                _this.vo_doctorlist.RegDate = daytime;
                _this.vo_doctorlist.DeptName = item.DeptName;
                _this.vo_doctorlist.DocName = item.EmpName;
                _this.vo_doctorlist.Describe = item.Describe;
                _this.vo_doctorlist.RankName = item.DoctorPost;
                _this.vo_doctorlist.HeadImg = item.HeadImg;
                var result = _this.service.countSchedule(allschedulelist, item.EmpId, daytime); //计算
                _this.vo_doctorlist.IsHave = result.IsHave;
                _this.vo_doctorlist.IsFull = result.IsFull; //计算
                _this.vo_doctorlist.HaveCount = result.HaveCount; //计算
                _this.vo_doctorlist.AllCount = result.AllCount;
                scheduledata.push(JSON.parse(JSON.stringify(_this.vo_doctorlist)));
            });
        }
        return { list: scheduledata };
    };
    //单个医生排班数据
    tsregisterController.prototype.doctorSchedule = function () {
        var _this = this;
        var deptId = TSLobsterAPI.Program.RequestQuery("deptId");
        var doctId = TSLobsterAPI.Program.RequestQuery("doctId");
        var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        var scheduledata = [];
        var docschedule = this.hisinterface.getdocOrderSched(0, doctId) || [];
        if (docschedule.length > 0) {
            docschedule[0].ItemA.forEach(function (item) {
                _this.vo_doctorschedule.RegId = item.RegId;
                _this.vo_doctorschedule.DeptId = item.DeptId;
                _this.vo_doctorschedule.DoctId = item.DoctId;
                _this.vo_doctorschedule.DeptName = item.DeptName;
                _this.vo_doctorschedule.DocName = item.DocName;
                _this.vo_doctorschedule.RegDate = item.RegDate;
                _this.vo_doctorschedule.TimeType = item.TimeType;
                _this.vo_doctorschedule.RegFee = item.RegFee;
                _this.vo_doctorschedule.Week = weekday[item.Week];
                _this.vo_doctorschedule.IsFull = 0;
                _this.vo_doctorschedule.IsHave = 0;
                _this.vo_doctorschedule.AllCount = 0;
                _this.vo_doctorschedule.HaveCount = 0;
                if (item.AllCount > 0) {
                    _this.vo_doctorschedule.IsHave = 1;
                    _this.vo_doctorschedule.AllCount = item.AllCount;
                    _this.vo_doctorschedule.HaveCount = item.HaveCount;
                    if (item.HaveCount == 0) {
                        _this.vo_doctorschedule.IsFull = 1;
                    }
                }
                scheduledata.push(JSON.parse(JSON.stringify(_this.vo_doctorschedule)));
            });
        }
        return { list: scheduledata };
    };
    //预约挂号，获取医生排班时段
    //互联网问诊，获取医生排班时段
    tsregisterController.prototype.dayTimeRange = function () {
        var _this = this;
        //let daytime = TSLobsterAPI.Program.RequestQuery("regdate", "");
        //schedtype 0 线下预约挂号 1线上互联网问诊
        var schedtype = TSLobsterAPI.Program.RequestQuery("schedtype");
        var deptId = TSLobsterAPI.Program.RequestQuery("deptId");
        var doctId = TSLobsterAPI.Program.RequestQuery("doctId");
        var nowdate = TSLobsterAPI.Utils.getCurrTime('yyyy-MM-dd');
        var allschedulelist = this.dao.getdocOrderSched(schedtype, deptId, doctId);
        //找出医生索引
        //let index = allschedulelist.map(x => { return x.DoctId; }).indexOf(parseInt(doctId));
        var timeRange = [];
        if (allschedulelist.length > 0) {
            allschedulelist[0].ItemA.forEach(function (item) {
                //获取时段
                //var rangelist = this.hisinterface.scheduleTimeRange(item.RegId) || [];
                var rangelist = _this.dao.scheduleTimeRange(item.RegId) || [];
                rangelist.forEach(function (range) {
                    _this.vo_doctorrange.DeptId = parseInt(deptId);
                    _this.vo_doctorrange.DoctId = parseInt(doctId);
                    _this.vo_doctorrange.RegDate = item.RegDate;
                    _this.vo_doctorrange.RegId = item.RegId;
                    _this.vo_doctorrange.Timeid = range.Timeid;
                    _this.vo_doctorrange.StartTime = range.StartTime;
                    _this.vo_doctorrange.EndTime = range.EndTime;
                    _this.vo_doctorrange.IsAll = 1;
                    _this.vo_doctorrange.Status = item.scheduleStatus;
                    _this.vo_doctorrange.TimeType = item.TimeType;
                    _this.vo_doctorrange.Week = item.Week;
                    _this.vo_doctorrange.RegFee = item.RegFee;
                    _this.vo_doctorrange.DeptName = item.DeptName;
                    _this.vo_doctorrange.DocName = item.DocName;
                    _this.vo_doctorrange.IsHave = 0;
                    _this.vo_doctorrange.HaveCount = 0;
                    _this.vo_doctorrange.AllCount = 0;
                    _this.vo_doctorrange.IsExpire = 0;
                    if (range.HaveCount > 0) {
                        _this.vo_doctorrange.IsHave = 1;
                        _this.vo_doctorrange.HaveCount = range.HaveCount;
                        _this.vo_doctorrange.AllCount = range.AllCount;
                    }
                    if (item.RegDate == nowdate) {
                        if (item.TimeType == 1 && new Date() > new Date(nowdate + ' 12:00:00')) {
                            _this.vo_doctorrange.IsExpire = 1;
                        }
                        else if (item.TimeType == 2 && new Date() > new Date(nowdate + ' 18:00:00')) {
                            _this.vo_doctorrange.IsExpire = 1;
                        }
                    }
                    timeRange.push(JSON.parse(JSON.stringify(_this.vo_doctorrange)));
                });
            });
        }
        return { list: timeRange };
    };
    /**
     * 预约挂号
     * 1、生成挂号记录，状态为待付款
     * 2、调用支付系统，付款
     * 3、调用his系统接口，挂号
     * 4、更新挂号记录，状态为已付款
     */
    tsregisterController.prototype.register = function () {
        var model = JSON.parse(TSLobsterAPI.Program.RequestBody());
        return this.service.register(model);
    };
    /**
     * 我的挂号记录
     */
    tsregisterController.prototype.getregrecordlist = function () {
        var pageInfo = {
            key: "Id desc",
            page: TSLobsterAPI.Program.RequestQuery("page", "1"),
            perPage: TSLobsterAPI.Program.RequestQuery("limit", "10"),
            totalRecord: 100
        };
        // var status = TSLobsterAPI.Program.RequestQuery('status');
        var patientId = TSLobsterAPI.Program.RequestQuery('PatientId', '0');
        var userId = TSLobsterAPI.Program.GetMPUserId();
        return this.dao.getregrecordlist(userId, patientId, pageInfo);
    };
    /**
     * 问诊记录
     */
    tsregisterController.prototype.getmedrecordlist = function () {
        var pageInfo = {
            key: "Id desc",
            page: TSLobsterAPI.Program.RequestQuery("page", "1"),
            perPage: TSLobsterAPI.Program.RequestQuery("limit", "10"),
            totalRecord: 100
        };
        //status 0问诊中 1已完成
        var status = TSLobsterAPI.Program.RequestQuery('status');
        var patientId = TSLobsterAPI.Program.RequestQuery('PatientId', '0');
        var userId = TSLobsterAPI.Program.GetMPUserId();
        return this.dao.getmedrecordlist(status, userId, patientId, pageInfo);
    };
    /**
     * 获取挂号记录详情
     */
    tsregisterController.prototype.getRegisterInfo = function () {
        var id = TSLobsterAPI.Program.RequestQuery('id');
        var info = this.dao.getRegisteredInfo(parseInt(id));
        return { info: info };
    };
    /**
     * 取消预约
     * 1、更新挂号记录中状态为退款中
     * 2、调用his接口，取消挂号记录
     * 3、调用支付系统，退款
     * 4、更新挂号记录中状态为退款完成
     */
    tsregisterController.prototype.cancelregister = function () {
        var id = TSLobsterAPI.Program.RequestQuery('id');
        return this.service.cancelregister(id);
    };
    /**
     * Web后台获取预约挂号记录
     */
    tsregisterController.prototype.getregrecordlist_web = function () {
        var pageInfo = {
            key: "Id desc",
            page: TSLobsterAPI.Program.RequestQuery("page", "1"),
            perPage: TSLobsterAPI.Program.RequestQuery("limit", "10"),
            totalRecord: 100
        };
        var sdate = TSLobsterAPI.Program.RequestQuery('sdate');
        var edate = TSLobsterAPI.Program.RequestQuery('edate');
        var status = TSLobsterAPI.Program.RequestQuery('status'); //0全部 1待支付 2已挂号 3已退款 4已取消
        var keyword = TSLobsterAPI.Program.RequestQuery('keyword') || '';
        return this.dao.getregrecordlist_web(sdate, edate, status, keyword, pageInfo);
    };
    /**
     * 医生信息界面，显示点赞最多的评价
     */
    tsregisterController.prototype.getevaluationtopone = function () {
        var doctId = TSLobsterAPI.Program.RequestQuery("doctId");
        var data = this.dao.getevaluationtopone(doctId);
        return { data: data };
    };
    /**
     * 更新评价点赞数
     */
    tsregisterController.prototype.updateevaluationgivecount = function () {
        var id = TSLobsterAPI.Program.RequestQuery("id");
        this.dao.updateevaluationgivecount(id);
        return { result: true };
    };
    tsregisterController.prototype.testsysconfig = function () {
        var appid = TSLobsterAPI.Program.GetAppId();
        var workid = TSLobsterAPI.Program.GetWorkId();
        var ret = TSLobsterAPI.AppFunction.GetSystemConfigs(workid, appid, 'SubMchId');
        return ret;
    };
    return tsregisterController;
}());

//author:kakake
var tsregisterService = /** @class */ (function () {
    function tsregisterService(workid) {
        this.data = {
            dbConn: TSLobsterAPI.Program.GetDbConn(),
            WorkId: 1
        };
        //挂号记录                                                                                                                                                                  
        this.do_registeredpayment = {
            model: {
                "Id": 0,
                "RegType": 1,
                "CardType": "",
                "CardNum": '',
                "MPUserID": "",
                "PatId": "",
                "PatName": "",
                "PatientId": 0,
                "HisEmpId": 0,
                "HisDeptId": 0,
                "DeptId": 0,
                "DeptName": "",
                "EmpId": 0,
                "EmpName": "",
                "Regid": "",
                "RegDate": "",
                "RegRange": "",
                "RegSchedType": 0,
                "Timeid": "",
                "PayMode": 1,
                "PayAmt": 0,
                "RegState": 0,
                "OrderState": 0,
                "CreateTime": "",
                "UpdateTime": "",
                "DeleteFlag": 0,
                "Sex": 0,
                "Birthday": "",
                "Phone": "",
                "WorkId": 1
            },
            tablename: "WPMT_RegisteredPayment",
            key: "Id",
            val: "0",
            objval: {},
            where: "",
            pageinfo: {},
            WorkId: 1
        };
        this.data.WorkId = workid;
        this.do_registeredpayment.WorkId = TSLobsterAPI.Program.GetWorkId();
        this.hisinterface = new tshisinterfaceController(1);
        this.dao = new tsregisterDao(this.data.WorkId);
    }
    //计算排班
    tsregisterService.prototype.countSchedule = function (allschedulelist, doctId, regdate) {
        var IsHave = 0; //无号
        var IsFull = 0;
        var AllCount = 0; //总号源数
        var HaveCount = 0; //剩余号源数
        //找出医生索引
        var index = allschedulelist.map(function (x) { return x.DoctId; }).indexOf(doctId);
        if (regdate) {
            if (index > -1) {
                //找出日期相同的索引
                var i_arr = allschedulelist[index].ItemA.map(function (x, i) {
                    if (x.RegDate == regdate) {
                        return i;
                    }
                    else {
                        return -1;
                    }
                });
                //过滤掉无效的索引
                i_arr = i_arr.filter(function (x) { return x >= 0; });
                if (i_arr.length > 0) {
                    IsHave = 1; //有号
                    //循环索引累加号源
                    i_arr.forEach(function (i) {
                        AllCount += parseInt(allschedulelist[index].ItemA[i].AllCount);
                        HaveCount += parseInt(allschedulelist[index].ItemA[i].HaveCount);
                    });
                    if (HaveCount == 0) {
                        IsFull = 1; //已约满
                    }
                }
            }
        }
        else {
            if (index > -1) {
                IsHave = 1; //有号
                //计算总号源
                AllCount = allschedulelist[index].ItemA.map(function (x) { return x.AllCount; }).reduce(function (a, b) { return parseInt(a) + parseInt(b); });
                //计算剩余号源
                HaveCount = allschedulelist[index].ItemA.map(function (x) { return x.HaveCount; }).reduce(function (a, b) { return parseInt(a) + parseInt(b); });
                if (HaveCount == 0) {
                    IsFull = 1; //已约满
                }
            }
        }
        return { IsHave: IsHave, IsFull: IsFull, HaveCount: HaveCount, AllCount: AllCount };
    };
    /**
     * 预约挂号
     * 1、生成挂号记录，状态为待付款
     * 2、调用支付系统，付款
     * 3、调用his系统接口，挂号
     * 4、更新挂号记录，状态为已付款
     */
    tsregisterService.prototype.register = function (model) {
        // var model = JSON.parse(TSLobsterAPI.Program.RequestBody());
        model.CreateTime = TSLobsterAPI.Utils.getCurrTime("yyyy-MM-dd HH:mm:ss");
        model.UpdateTime = TSLobsterAPI.Utils.getCurrTime("yyyy-MM-dd HH:mm:ss");
        model.HisEmpId = model.EmpId;
        model.HisDeptId = model.DeptId;
        model.RegState = 1; //预约中
        model.PayMode = 1; //微信
        model.OrderState = 1; //订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        model.WorkId = TSLobsterAPI.Program.GetWorkId();
        this.do_registeredpayment.objval = model;
        TSLobsterAPI.DbHelper.SaveModel(this.data.dbConn, this.do_registeredpayment);
        model.Id = this.do_registeredpayment.objval['Id'];
        var workid = TSLobsterAPI.Program.GetWorkId();
        var appid = TSLobsterAPI.Program.GetAppId();
        var ret = TSLobsterAPI.AppFunction.GetSystemConfigs(workid, appid, 'SubMchId');
        // TSLobsterAPI.Utils.TrackLog('SubMchId',ret);
        if (!ret.data.config.SubMchId) {
            throw '系统参数SubMchId没有配置';
        }
        //获取收银台页面
        var param = {
            SubMchId: ret.data.config.SubMchId,
            BusinessOrderNo: model.Id.toString(),
            OrderType: 1,
            PayType: 1,
            PayScene: 1,
            Price: model.PayAmt * 100,
            Body: '预约挂号',
            Memo: '备注' //可以不填
        };
        // TSLobsterAPI.Utils.TrackLog('param',param);
        var res = TSLobsterAPI.AppFunction.CallOutService(appid, 'pay.pay.preorder', param);
        TSLobsterAPI.Utils.TrackLog('payredirecturl', res);
        var url = res.data.payredirecturl; //收银台界面，支付成功后回调订阅服务register.register.toregister，然后会调用his接口
        //测试支付成功后调用his接口
        // this.registerpaysuccess({ BusinessOrderNo: model.Id });
        return { result: true, url: url };
    };
    /**
     * 取消预约
     * 1、更新挂号记录中状态为退款中
     * 2、调用his接口，取消挂号记录
     * 3、调用支付系统，退款
     * 4、更新挂号记录中状态为退款完成
     */
    tsregisterService.prototype.cancelregister = function (id) {
        // var id = TSLobsterAPI.Program.RequestQuery('id');
        var info = this.dao.getRegisteredInfo(parseInt(id));
        if (info) {
            if (info.GetNumberState == 1) {
                throw "已取号，无法取消";
            }
            if (info.RegState > 2) {
                throw "无法取消";
            }
            if (info.RegState == 1 || info.RegState == 2) {
                this.dao.cancelregister(parseInt(id));
                this.hisinterface.cancelregister({ Regno: info.RegNo, RegDate: info.RegDate });
                //调用支付系统退款接口
                //this.cancelregisterrefundsuccess({BusinessOrderNo:id});
                var workid = TSLobsterAPI.Program.GetWorkId();
                var appid = TSLobsterAPI.Program.GetAppId();
                var ret = TSLobsterAPI.AppFunction.GetSystemConfigs(workid, appid, 'SubMchId');
                // TSLobsterAPI.Utils.TrackLog('SubMchId',ret);
                if (!ret.data.config.SubMchId) {
                    throw '系统参数SubMchId没有配置';
                }
                var param = {
                    SubMchId: ret.data.config.SubMchId,
                    BusinessOrderNo: id.toString(),
                    BusinessRefundNo: info.RegNo,
                    PayType: 1,
                    RefundRealFee: parseFloat(info.PayAmt) * 100,
                    RefundDesc: '预约挂号退款'
                };
                // TSLobsterAPI.Utils.TrackLog('param',param);
                var res = TSLobsterAPI.AppFunction.CallOutService(appid, 'pay.pay.refund', param);
                TSLobsterAPI.Utils.TrackLog('pay.pay.refund', res);
            }
        }
        else {
            throw '记录不存在';
        }
        return { result: true };
    };
    /**
     * 支付回调成功
     */
    tsregisterService.prototype.registerpaysuccess = function (backpayobj) {
        //let TranSerNo = '';
        //let OrderNo = '';
        var PayMode = 1; //1微信
        var reginfo = this.dao.getRegisteredInfo(parseInt(backpayobj.BusinessOrderNo));
        var param2 = {
            DeptId: reginfo.DeptId,
            DoctId: reginfo.EmpId,
            Regid: reginfo.Regid,
            RegDate: reginfo.RegDate,
            Timeid: reginfo.Timeid,
            CardType: reginfo.CardType,
            CardNum: reginfo.CardNum,
            TranSerNo: backpayobj.TransactionId,
            PayTime: TSLobsterAPI.Utils.getCurrTime(null),
            PayMode: PayMode,
            TotalRegFee: reginfo.PayAmt
        };
        var ret2 = this.hisinterface.register(param2);
        if (ret2.result) {
            var regno = ret2.Regno; //挂号id
            var location = ret2.Location; //科室地址
            this.dao.updateRegPayed(parseInt(backpayobj.BusinessOrderNo), regno, location, backpayobj.TransactionId, backpayobj.OrderNo, PayMode);
        }
        else {
            throw '调用his接口失败';
        }
        return { result: true };
    };
    /**
     * 退款成功回调
     * 更新挂号记录中状态为退款完成
     */
    tsregisterService.prototype.cancelregisterrefundsuccess = function (backrefundobj) {
        this.dao.cancelregisterfinshed(parseInt(backrefundobj.BusinessOrderNo), backrefundobj.RefundNo, backrefundobj.RefundTransactionId);
        return { result: true };
    };
    return tsregisterService;
}());

//author:kakake
var tsregisterDao = /** @class */ (function () {
    function tsregisterDao(workid) {
        this.data = {
            dbConn: TSLobsterAPI.Program.GetDbConn(),
            WorkId: 1
        };
        this.data.WorkId = workid;
    }
    //获取科室分类和科室
    tsregisterDao.prototype.getdept = function () {
        // var strsql = "SELECT *  FROM WPMT_BaseDeptLayer where workid=@workid ";
        // var strsql2 = "SELECT *  FROM WPMT_BaseDept a   where a.workid=@workid ";
        var strsql = "SELECT *  FROM WPMT_BaseDeptLayer ";
        var strsql2 = "SELECT *  FROM WPMT_BaseDept a ";
        var layer = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, { workid: this.data.WorkId });
        var dept = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql2, { workid: this.data.WorkId });
        return { layer: layer, dept: dept };
    };
    //预约排班
    //显示医生以及医生各个时段的号源
    //schedtype 0 线下预约挂号 1线上互联网问诊
    tsregisterDao.prototype.getdocOrderSched = function (schedtype, _deptId, _empId) {
        var _this = this;
        var deptId = _deptId || 0;
        var empId = _empId || 0;
        //a.workid=b.workid and
        //a.workid=c.workid and
        var strsql = "SELECT a.DeptID DeptId,a.DoctID DoctId,0 GoodNum,0 RegNum,isnull(b.Name,'') DeptName,isnull(c.EmpName,'') DocName FROM WPMT_DocSchedual a \
                        left join wpmt_basedept b on  a.DeptID=b.DeptId \
                        left join wpmt_doctor c on  a.DoctID=c.EmpId \
                        where a.SchedType=@schedtype and (a.DeptID=@deptId or 0>=@deptId) and (a.DoctID=@empId or 0>=@empId) AND \
                        SchedualDate>=CONVERT(varchar(10), GETDATE(), 120) AND \
                        SchedualDate<=CONVERT(varchar(10), DATEADD(DAY,6,GETDATE()),120) \
                        GROUP BY a.DeptID,a.DoctID,b.Name,c.EmpName";
        var dbparams = {
            schedtype: schedtype,
            deptId: deptId,
            empId: empId
        };
        var Items = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams);
        //a.workid=b.workid and
        //a.workid=c.workid and
        Items.forEach(function (i) {
            strsql = "SELECT a.SchedualID RegId \
                        ,a.DeptID DeptId \
                        ,a.DoctID DoctId \
                        ,isnull(b.Name,'') DeptName \
                        ,isnull(c.EmpName,'') DocName \
                        ,CONVERT(varchar(10), SchedualDate, 120) RegDate \
                        ,Datepart(weekday, SchedualDate + @@DateFirst - 1) Week \
                        ,c.RegPrice RegFee \
                        ,a.TimeRange TimeType  \
                        ,a.AppointNum AllCount \
                        ,(a.AppointNum-(select COUNT(1) from WPMT_RegisteredPayment t where t.Regid=a.SchedualID and t.RegState=2)) HaveCount \
                        ,a.Flag scheduleStatus \
                        FROM WPMT_DocSchedual a \
                        left join wpmt_basedept b on  a.DeptID=b.DeptId \
                        left join wpmt_doctor c on  a.DoctID=c.EmpId \
                        where a.SchedType=@schedtype and a.DeptID=@DeptId and a.DoctID=@DoctId AND \
                        SchedualDate>=CONVERT(varchar(10), GETDATE(), 120) \
                        AND SchedualDate<=CONVERT(varchar(10), DATEADD(DAY,6,GETDATE()),120) order by a.SchedualDate,a.TimeRange";
            var dbparams2 = {
                schedtype: schedtype,
                DeptId: i.DeptId,
                DoctId: i.DoctId
            };
            i.scheduleStatus = 0;
            i.ItemA = TSLobsterAPI.DbHelper.DbGetJsonData(_this.data.dbConn, strsql, dbparams2);
        });
        return Items;
    };
    //排班时间段
    tsregisterDao.prototype.scheduleTimeRange = function (_regid) {
        //1.查询指定号源的时段
        var strsql = "SELECT TOP 1 \
                        TimeRange Timeid \
                        ,case TimeRange WHEN 1 then '8:30' when 2 then '14:00'  else '18:00' end StartTime \
                        ,case TimeRange WHEN 1 then '12:00' when 2 then '18:00' else '23:00' end EndTime \
                        ,AppointNum AllCount \
                        ,(a.AppointNum-(select COUNT(1) from WPMT_RegisteredPayment t where t.Regid=a.SchedualID and t.RegState=2)) HaveCount \
                        FROM WPMT_DocSchedual a where SchedualID=@regid";
        var dbparams = {
            regid: _regid
        };
        var Items = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams);
        return Items;
    };
    /**
     * 获取医生列表
     */
    tsregisterDao.prototype.getDoctorList = function (deptId) {
        deptId = deptId || 0;
        // let strsql = 'SELECT * FROM WPMT_Doctor where WorkId=@workid';
        var strsql = 'SELECT * FROM WPMT_Doctor where 1=1 ';
        if (deptId > 0) {
            strsql += ' and DeptId=@deptId';
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, { workid: this.data.WorkId, deptId: deptId });
        return data;
    };
    /**
     * 获取医生列表，分页
     */
    tsregisterDao.prototype.getDoctorPageList = function (pageInfo, search) {
        // var strsql = "SELECT * FROM WPMT_Doctor where WorkId=@workid and EmpName like @search";
        var strsql = "SELECT * FROM WPMT_Doctor where EmpName like @search";
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, { workid: this.data.WorkId, search: '%' + search + '%' }, pageInfo);
        return { list: data, count: pageInfo.totalRecord };
    };
    /**
     * 医生详情
     */
    tsregisterDao.prototype.getDoctorInfo = function (empId) {
        // let strsql = "select * from WPMT_Doctor where WorkId=@workid and EmpId=@empId";
        var strsql = "select * from WPMT_Doctor where EmpId=@empId";
        return TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, { empId: empId, workid: this.data.WorkId });
    };
    /**
     * 挂号记录
     */
    tsregisterDao.prototype.getregrecordlist = function (userId, patientId, pageInfo) {
        var dbparams = {
            workid: this.data.WorkId,
            userId: userId,
            PatientId: patientId
        };
        var strsql = "select r.*, isnull(d.HeadImg,'') UPic from WPMT_RegisteredPayment r left join WPMT_Doctor d on r.EmpId = d.EmpId \
        where r.RegType=1 and r.RegState in (2,4) and r.WorkId=@workid and MPUserID=@userId ";
        //RegState 1 预约中 2 预约成功 3 预约失败 4预约取消
        //OrderState 订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        if (parseInt(patientId) > 0) {
            strsql += " and r.PatientId=@PatientId";
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { list: data, count: pageInfo.totalRecord };
    };
    /**
     * 问诊记录
     * status 0问诊中 1已完成
     */
    tsregisterDao.prototype.getmedrecordlist = function (status, userId, patientId, pageInfo) {
        var dbparams = {
            workid: this.data.WorkId,
            userId: userId,
            PatientId: patientId
        };
        var strsql = "select r.*, isnull(d.HeadImg,'') UPic from WPMT_RegisteredPayment r left join WPMT_Doctor d on r.EmpId = d.EmpId \
        where r.RegType=2 and r.WorkId=@workid and MPUserID=@userId ";
        //RegState 1 预约中 2 预约成功 3 预约失败 4预约取消
        //OrderState 订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        if (parseInt(patientId) > 0) {
            strsql += " and r.PatientId=@PatientId";
        }
        if (parseInt(status) == 0) {
            strsql += " and r.RegState=2 ";
        }
        else if (parseInt(status) == 1) {
            strsql += " and r.RegState>2 ";
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { list: data, count: pageInfo.totalRecord };
    };
    /**
     * 挂号记录详情
     */
    tsregisterDao.prototype.getRegisteredInfo = function (id) {
        var strsql = "select * from WPMT_RegisteredPayment where Id=@id";
        return TSLobsterAPI.DbHelper.DbGetJsonObject(this.data.dbConn, strsql, { id: id });
    };
    /**
     * 后台查询挂号记录
     */
    tsregisterDao.prototype.getregrecordlist_web = function (sdate, edate, status, keyword, pageInfo) {
        var dbparams = {
            workid: this.data.WorkId,
            sdate: sdate,
            edate: edate,
            status: status,
            keyword: "%" + keyword + "%"
        };
        //RegState 1 预约中 2 预约成功 3 预约失败 4预约取消
        //OrderState 订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        var strsql = "select * from WPMT_RegisteredPayment  where WorkId=@workid and PatName like @keyword and RegDate BETWEEN @sdate and @edate";
        if (parseInt(status) > 0) {
            if (parseInt(status) == 1) {
                strsql += ' and OrderState=1';
            }
            else if (parseInt(status) == 2) {
                strsql += ' and OrderState=2';
            }
            else if (parseInt(status) == 3) {
                strsql += ' and OrderState=7';
            }
            else if (parseInt(status) == 4) {
                strsql += ' and OrderState=5';
            }
        }
        var data = TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, dbparams, pageInfo);
        return { list: data, count: pageInfo.totalRecord };
    };
    //更新已支付状态
    tsregisterDao.prototype.updateRegPayed = function (Id, RegNo, Location, TranSerNo, OrderNo, PayMode) {
        var strsql = " update WPMT_RegisteredPayment set RegState=2,OrderState=2,OrderNo=@OrderNo,PayTime=@PayTime,PayMode=@PayMode,TranSerNo=@TranSerNo,Waitno=@Waitno,RegNo=@RegNo,PatId=@PatId,Location=@Location where Id=@Id";
        var dbparams = {
            Id: Id,
            RegNo: RegNo,
            Location: Location,
            TranSerNo: TranSerNo,
            OrderNo: OrderNo,
            PayTime: TSLobsterAPI.Utils.getCurrTime(null),
            PayMode: PayMode,
            Waitno: '',
            PatId: RegNo
        };
        TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, dbparams);
    };
    /**
     * 退款中
     */
    tsregisterDao.prototype.cancelregister = function (id) {
        //RegState 1 预约中 2 预约成功 3 预约失败 4预约取消
        //OrderState 订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        var strsql = " update WPMT_RegisteredPayment set OrderState=6 where Id=@id";
        var dbparams = {
            id: id
        };
        TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, dbparams);
    };
    /**
     * 退款完成
     */
    tsregisterDao.prototype.cancelregisterfinshed = function (id, RefundNo, RefundTransactionId) {
        //RegState 1 预约中 2 预约成功 3 预约失败 4预约取消
        //OrderState 订单状态: 1待付款、2已付款、5已取消、6退款中、7退款完成、
        var strsql = " update WPMT_RegisteredPayment set RegState=4,GetNumberState=9,OrderState=7,OrderNo_Refund=@RefundNo,TranSerNo_Refund=@RefundTransactionId where Id=@id";
        var dbparams = {
            id: id,
            RefundNo: RefundNo,
            RefundTransactionId: RefundTransactionId
        };
        TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, dbparams);
    };
    /**
    * 医生信息界面，显示点赞最多的评价
    */
    tsregisterDao.prototype.getevaluationtopone = function (doctId) {
        var strsql = "select top 1 * from WPMT_DoctorEvaluation where workid=@workid and status=1 and EmpId=@doctId order by givecount desc";
        return TSLobsterAPI.DbHelper.DbGetJsonData(this.data.dbConn, strsql, { workid: this.data.WorkId, doctId: doctId });
    };
    /**
     * 更新评价点赞数
     */
    tsregisterDao.prototype.updateevaluationgivecount = function (id) {
        var strsql = "update WPMT_DoctorEvaluation set givecount=isnull(givecount,0)+1 where ID=@id";
        TSLobsterAPI.DbHelper.DbExecuteUpdate(this.data.dbConn, strsql, { id: id });
    };
    return tsregisterDao;
}());

